package DB;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;

public class DBCon {
	private static final String url = "jdbc:sqlserver://balder.ucn.dk:1433;database=dmaj0913_5;user=dmaj0913_5;password=IsAllowed";
	private DatabaseMetaData meta;
	private static Connection con;
	private static DBCon instance = null;

	private DBCon() {
		try {
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			System.out.println("Driver Class loaded succesfully");

		} catch (Exception e) {
			System.out.println("Error! Cannot find the driver");
			e.printStackTrace();
		}
		try {
			con = DriverManager.getConnection(url);
			con.setAutoCommit(true);
			meta = con.getMetaData();
			System.out.println("Connection to " + meta.getURL());
			System.out.println("Driver " + meta.getDriverName());
			System.out.println("Database product name "
					+ meta.getDatabaseProductName());
		} catch (Exception e) {
			e.printStackTrace();

		}
	}

	public Connection getDBCon() {
		return con;

	}

	public static DBCon getInstance() {
		if (instance == null) {
			instance = new DBCon();
		}
		return instance;
	}

	public static void startTransaction() {
		try {
			con.setAutoCommit(true);

		} catch (Exception e) {
			System.out.println("Failed to start the transaction with the DB!");
			e.printStackTrace();

		}
	}

	public static void commit() {
		try {
			con.setAutoCommit(true);
		} catch (Exception e) {
			System.out.println("Failed to commit the transaction with the DB!");
			e.printStackTrace();
		}
	}

	public static void rollback() {
		try {
			con.rollback();
			con.setAutoCommit(true);
		} catch (Exception e) {
			System.out.println("Failed to rollback the transaction!");
			e.printStackTrace();
		}
	}

	public static void close() {
		try {
			con.close();
			System.out.println("Connection closed!");
		} catch (Exception e) {
			System.out
					.println("Error trying to close the connection to the DB!");
			e.printStackTrace();
		}
	}
}
